package servlet.XMLTree;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import offer.GetDataSource;
import offer.SessionObj;
import offer.system.ModuleStatus;


import com.netscenery.yang.model.*;

import system.bean.Member;
import system.bean.ModuleDocument;
import system.dao.DocumentDao;

public class CreateNewModuleServlet extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public CreateNewModuleServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out
				.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.print("    This is ");
		out.print(this.getClass());
		out.println(", using the GET method");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/xml; charset=utf-8");
		request.setCharacterEncoding("utf-8");
		response.setHeader("Cache-Control","no-cache"); 
		PrintWriter    out = response.getWriter();
		String  ModuleName = request.getParameter("ModuleName");
		String _mainModule = request.getParameter("_mainModule");
		
		SessionObj sessionObj = (SessionObj)request.getSession().getAttribute("sessionObj");
		Member member = sessionObj.getMember();
		
		String msgString = "";
		String urlString ="/demo.jsp";
		DocumentDao documentDao  = new DocumentDao();
		ModuleDocument mDocument = new ModuleDocument();
		
		Module module = null;
		Env env = null;
		mDocument.setMemberId(member.getMemberId());
		mDocument.setDocName(ModuleName.trim());
		SubModule subModule = null;
		if(documentDao.isMemberDocExist(mDocument)){
			msgString = "�Ը����������ģ���ļ����Ѿ����ڣ�";
			urlString ="/GoToIndexServlet";
		}else{
			if(null != _mainModule && !"".equalsIgnoreCase(_mainModule)){
				module = GetDataSource.getMainModuleByName(request, _mainModule.trim());
				if(null == module){
					msgString = "����5�ĸ�ģ�鲻���ڣ�";
					urlString ="/GoToIndexServlet";
				}else{
					env = new Env();
					env.addMainModule((MainModule)module);
					try {
						subModule = new SubModule(env,ModuleName,module.getName(),((MainModule)module).getPrefix());
					} catch (ModelException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					createRootNodeForModule(request,subModule);
					sessionObj.setModule(subModule);
					sessionObj.setCurDocID(-1);                //��ǰģ����ϵͳ�в�����
				}
			}else{
				env = new Env();
				try {
					module = new MainModule(env, ModuleName);
				} catch (ModelException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				createRootNodeForModule(request,module);;
				sessionObj.setModule(module);
				sessionObj.setCurDocID(-1);                //��ǰģ����ϵͳ�в�����
			}
		}
		sessionObj.setModuleStatus(ModuleStatus.EDITING);
		request.setAttribute("NewModuleMsg", msgString);
		ServletContext sc=this.getServletContext();
		RequestDispatcher rd=sc.getRequestDispatcher(urlString);
		rd.forward(request, response);
		
		out.flush();
		out.close();
	}
	
	private void createRootNodeForModule(HttpServletRequest request, Module module)
		throws ServletException, IOException {
		String _Configuration = request.getParameter("_configurationNode");
		String _StateNode     = request.getParameter("_stateNode");
		
		if(null != _Configuration && !"".equalsIgnoreCase(_Configuration)){

			Node confNode = module.createDataDef("container", _Configuration);
			module.addNode(confNode);
		}
		
		if(null != _StateNode && !"".equalsIgnoreCase(_StateNode)){

			Node stateNode = module.createDataDef("container", _StateNode);
			module.addNode(stateNode);
		}
		
	}
	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
